package com.qd.aliyun.listener;

import com.alicom.mns.tools.MessageListener;
import com.aliyun.mns.model.Message;
import com.cdqidi.util.DateUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qd.aliyun.dto.AliYunSmsReportDTO;
import com.qd.common.sys.domain.entity.msg.MsgReportDTO;
import com.qd.system.service.msg.base.MsgReportService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

/**
 * 阿里云短信状态报告
 *
 * @author sjk
 */
@Slf4j
public class AliYunSmsReportMsgListener implements MessageListener {
    private final ObjectMapper objectMapper;
    private final MsgReportService msgReportService;

    public AliYunSmsReportMsgListener(ObjectMapper objectMapper, MsgReportService msgReportService) {
        this.objectMapper = objectMapper;
        this.msgReportService = msgReportService;
    }

    @Override
    public boolean dealMessage(Message message) {
        //消息的几个关键值
        if(log.isDebugEnabled()) {
            log.debug("message receiver time from mns:{}", LocalDateTime.now());
            log.debug("message handle: {}", message.getReceiptHandle());
            log.debug("message body: {}", message.getMessageBodyAsString());
            log.debug("message id: {}", message.getMessageId());
            log.debug("message dequeue count:{}", message.getDequeueCount());
            log.debug("Thread:{}", Thread.currentThread().getName());
        }
        try {
            AliYunSmsReportDTO report = objectMapper.readValue(message.getMessageBodyAsString(), AliYunSmsReportDTO.class);
            log.info("阿里云短信回执: {}", report);
            saveMsgReport(report);
            report.freeData();
        } catch (JsonProcessingException e) {
            log.error("阿里云短信状态报告异常", e);
            //理论上不会出现格式错误的情况，所以遇见格式错误的消息，只能先delete,否则重新推送也会一直报错
            return true;
        } catch (Throwable e) {
            //您自己的代码部分导致的异常，应该return false,这样消息不会被delete掉，而会根据策略进行重推
            return false;
        }
        return true;
    }

    private void saveMsgReport(AliYunSmsReportDTO report) {
        MsgReportDTO msgReportDTO = new MsgReportDTO();
        msgReportDTO.setMsgId(report.getBizId());
        msgReportDTO.setAddTime(LocalDateTime.now());
        msgReportDTO.setReportTime(DateUtil.strToLocalDateTime(report.getReportTime()));
        msgReportDTO.setSendResult(report.getSuccess() ? 1 : 2);
        if (StringUtils.hasLength(report.getErrCode())) {
            msgReportDTO.setErrCode(report.getErrCode());
        }
        if (StringUtils.hasLength(report.getErrMsg())) {
            msgReportDTO.setErrMsg(report.getErrMsg());
        }
        msgReportService.save(msgReportDTO);
        msgReportDTO.freeData();
    }
}
